package com.qianli.cashmama.product.server.job;

import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.fqgj.common.api.Page;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.DateUtil;
import com.fqgj.common.utils.StringUtils;
import com.google.gson.Gson;
import com.jsoniter.JsonIterator;
import com.jsoniter.output.JsonStream;
import com.qianli.cashmama.product.server.dao.PayCallbackLogDao;
import com.qianli.cashmama.product.server.dao.PayRequestLogDao;
import com.qianli.cashmama.product.server.entity.PayCallbackLogEntity;
import com.qianli.cashmama.product.server.entity.PayRequestLogEntity;
import com.qianli.cashmama.product.server.entity.TBillEntity;
import com.robert.vesta.util.IpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: sm
 * Date: 2021/12/7
 * Time: 12:08 下午
 */
@Service
public class TigerPayCallBackToBizJob {
    private static final Logger logger = LoggerFactory.getLogger(TigerPayCallBackToBizJob.class);

    private static final String bizRepaymentCallBackUrl = "http://open-api.rupee-mama.in/api.repayment.result";
    private static final String collection_url = "http://147.139.66.58:9108/collection/receive/repayment";

    @Autowired
    private PayCallbackLogDao payCallbackLogDao;

    @Autowired
    private PayRequestLogDao payRequestLogDao;

    @NacosValue(value = "${job.run.ip:0}", autoRefreshed = true)
    private String jobRunIp;

    @NacosValue(value = "${pay.call.back.to.biz.switch:false}", autoRefreshed = true)
    private Boolean paySwitch;

    @Scheduled(fixedDelay = 1000L * 30)
    public void run() {

        String hostIp = IpUtils.getHostIp();
        logger.info("==TigerPayCallBackToBizJob==,ip:{}", hostIp);

        if (!hostIp.equals(jobRunIp)) {
            logger.info("==TigerPayCallBackToBizJob==, 当前机器ip不是job执行机器,当前iP:{},目标IP:{}", hostIp, jobRunIp);
            return;
        }

        if (!paySwitch) {
            logger.info("==TigerPayCallBackToBizJob  switch not open==");
            return;
        }

        tellDc();
    }


    public void tellDc() {
        Page page = new Page();
        page.setCurrentPage(1);
        page.setPageSize(100);

        List<PayCallbackLogEntity> listByStatus = payCallbackLogDao.getListByStatus(0, page);

        if (CollectionUtils.isEmpty(listByStatus)) {
            logger.info("==TigerPayCallBackToBizJob  size===0  ==");
            return;
        }
        logger.info("==TigerPayCallBackToBizJob==,size:{}", listByStatus.size());
        listByStatus.forEach(payCallbackLogEntity -> {
            payCallbackLogEntity.setStatus(1);
            try {
                PayRequestLogEntity payRequestLogEntity = payRequestLogDao.selectByTripleOrderNo(payCallbackLogEntity.getTradeNo());
                String paidAmount = payCallbackLogEntity.getOrderAmount().toString();
                boolean tellCollectionSuccess = tellCollection(payRequestLogEntity.getTradeNo(), paidAmount, payCallbackLogEntity.getPayOrderId());
                if (!tellCollectionSuccess) {
                    payCallbackLogEntity.setStatus(3);
                }

            } catch (Exception e) {
                payCallbackLogEntity.setStatus(2);
                logger.error("== 回调给业务端失败 异常==", e);
            }

            payCallbackLogDao.updateByPrimaryKey(payCallbackLogEntity);

        });
    }

    public boolean tellCollection(String tradeNo, String paidAmount, String repayBizNo) {

        try {
//            TBillEntity bill = payCallbackLogDao.getBillByTradeNo(tradeNo);
//            logger.info("==tellCollection ==,bill:{}", JsonStream.serialize(bill));
//            String token = getToken(bill.getProductCategory());

//            if (StringUtils.isEmpty(token)) {
//                logger.error("== 推送到催收找不到token ==,productCategory:{},tradeNo:{}", bill.getProductCategory(), tradeNo);
//                return false;
//            }

            ClRepaymentRequest request = new ClRepaymentRequest()
                    .setDeductAmount("0")
                    .setOrderBillNo(tradeNo)
                    .setPaidAmount(paidAmount)
                    .setPaidStatus(2)
                    .setPaidType(1)
                    .setRepayBizNo(repayBizNo)
                    .setRepayDate(DateUtil.getDate(new Date(), "yyyy-MM-dd HH:mm:ss"))
                    .setToken("token")
                    .setTotalDeductAmount("0")
                    .setTotalPaidAmount(paidAmount)
                    .setTradeNo(tradeNo);

            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/json;charset=utf-8");

            HttpEntity requestPush = new HttpEntity(JsonStream.serialize(request), headers);
            ResponseEntity responseEntity = new RestTemplate().postForEntity(collection_url, requestPush, String.class);
            String responseStr = responseEntity.getBody().toString();
            logger.info("=======  推送collection请求结果  ======:{},method:{}", responseStr, collection_url);
            return JsonIterator.deserialize(responseStr).get("code").toString().equals("0");
        } catch (Exception e) {
            logger.error("=======  推送collection请求结果 error  ======", e);
            return false;
        }


    }

    public static String getToken(String productCategory) {
        Map<String, String> map = new HashMap<>();

        map.put("loanZoneAll", "f3feccf382016e9c3b28d9e7d843a2a8");
        map.put("cashZoneAll", "a17c476ce94aeb6c7b79d094eb4c607a");
        map.put("meraLoanAll", "f2c31cdcbabacc641f22719a8b8d451b");

        if (!map.containsKey(productCategory)) {
            return null;
        }

        return map.get(productCategory);

    }

    public static void main(String[] args) {
        long time = new Date().getTime();
        Date date = DateUtil.getDate("2021-11-01 00:00:00", "yyyy-MM-dd HH:mm:ss");
        String date1 = DateUtil.getDate(new Date(), "yyyy-MM-dd HH:mm:ss");

        System.err.println(11);
    }
}
